<template>
  <div class="fileCollectionWrapper">
    <image-review-dialog v-model="imageReviewDialog" :url="showUrl"/>
    <ul class="list">
      <li class="li" v-for="(item, index) in queryList" :key="index">
        <el-card :class="{card: true, cardSelect: item && item.select}" shadow="always">
          <div class="wrapper">
            <!--suppress HtmlUnknownTarget -->
            <el-image class="img" :src="item['base64'] || item['url']"
                      :alt="item['url']"/>
            <div class="maskUploading" v-if="item['state'] === 'uploading'">
              <div class="maskIcon">
                <el-progress class="progress" type="circle" :width="60" :percentage="item['progress']"/>
              </div>
            </div>
            <div class="maskMenu" @click="handleSelect(item)" v-if="item['state'] === 'finish'">
              <el-button type="primary" @click.stop="showImage(item)" circle size="small" icon="el-icon-view"/>
              <el-button type="danger" @click.stop="removeImage(item)" circle size="small" icon="el-icon-delete-solid"/>
              <el-button type="info" @click.stop="downloadImage(item)" circle size="small" icon="el-icon-download"/>
            </div>
          </div>
        </el-card>
      </li>
      <li class="li" v-for="(item, index) in list" :key="index + (item['id'] ? item['id'] : 0)">
        <el-card :class="{card: true, cardSelect: item && item.select}" shadow="always">
          <div class="wrapper">
            <!--suppress HtmlUnknownTarget -->
            <el-image class="img" :src="item['base64'] || item['url']"
                      :alt="item['url']"/>
            <div class="maskUploading" v-if="item['state'] === 'uploading'">
              <div class="maskIcon">
                <el-progress class="progress" type="circle" :width="60" :percentage="item['progress']"/>
              </div>
            </div>
            <div class="maskMenu" @click="handleSelect(item)" v-if="item['state'] === 'finish'">
              <el-button type="primary" @click="showImage(item)" circle size="small" icon="el-icon-view"/>
              <el-button type="danger" @click="removeImage(item)" circle size="small" icon="el-icon-delete-solid"/>
              <el-button type="info" @click="downloadImage(item)" circle size="small" icon="el-icon-download"/>
            </div>
          </div>
        </el-card>
      </li>
      <li class="li" v-if="!queryLoading">
        <el-card class="card" shadow="always" @click.native="addImage">
          <el-image class="img" src=""/>
        </el-card>
      </li>
      <li class="li" v-if="queryLoading">
        <el-card class="card" shadow="always">
          <div class="wrapper" style="background: #44444444">
            <i class="el-icon-loading loading"/>
          </div>
        </el-card>
      </li>
    </ul>
    <input type="file" ref="fileInput" @change="fileChange" multiple="multiple"
           accept="image/x-png,image/gif,image/jpeg,image/bmp" style="display: none;"/>
  </div>
</template>

<script>

import { queryCollectionsByUserWithName,
  removeByIds,
  uploadCollectionFile } from '@/api/ApiFileCollection'
import { ResultCode } from '@/constants/constants'
import { getBase64 } from '@/utils/Utils'
import ImageReviewDialog from '@/components/upload/ImageReviewDialog'
import { downloadUrlFile } from '@utils/FileUtils'

export default {
  name: 'FileCollection',
  components: { ImageReviewDialog },
  props: {
    name: {
      required: false,
      type: String,
      default: 'test'
    },
    multiple: {
      required: false,
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      queryLoading: false,
      downLoading: false,
      imageReviewDialog: false,
      queryList: [],
      list: [],
      showUrl: ''
    }
  },
  computed: {
  },
  mounted () {
    this.queryData()
  },
  methods: {
    /**
     * 转换查询的数据
     */
    convertQueryData (item) {
      item.state = 'finish'
      item.progress = 0
      item.select = false
      return item
    },
    /**
     * 查询数据
     */
    queryData () {
      if (this.queryLoading) {
        return
      }
      if (this.name) {
        this.queryLoading = true
        queryCollectionsByUserWithName(this.name, data => {
          if (data && data.code === ResultCode.OK) {
            this.list = []
            data = data.object
            if (data && typeof data === 'object') {
              const temp = []
              data.forEach(item => {
                temp.push(this.convertQueryData(item))
              })
              this.queryList = temp
            }
          }
        }, () => {
          this.queryLoading = false
        })
      } else {
        this.list = []
        this.queryList = []
      }
    },
    /**
     * 添加文件点击回调
     */
    addImage () {
      this.$refs['fileInput'].click()
    },
    /**
     * 选择文件改变
     */
    fileChange (val) {
      const files = val.target.files
      if (files && typeof files === 'object') {
        files.forEach(item => {
          this.uploadFile(item)
        })
      }
    },
    createUploadItem (file) {
      return new Promise(function (resolve) {
        getBase64(file).then(value => {
          const item = {
            id: new Date().getTime(),
            url: '',
            file: file,
            select: false,
            state: 'uploading',
            progress: 0,
            base64: value
          }
          resolve(item)
        })
      })
    },
    /**
     * 上传单个文件
     * @param {Object} file 文件
     */
    uploadFile (file) {
      this.createUploadItem(file).then(item => {
        this.list.push(item)
        uploadCollectionFile(item.file, this.name, (next) => {
          const pro = next.total.percent
          if (pro) {
            item.progress = Math.ceil(pro)
          }
        }, success => {
          if (success && success.code === ResultCode.OK) {
            item.progress = 100
            const data = success.object
            item.id = data['id']
            item.url = data['image']
            item.fileId = data['imageFileId']
            item.state = 'finish'
          }
        })
      })
    },
    /**
     * 查看文件
     * @param item 图片信息元素
     */
    showImage (item) {
      if (item) {
        this.showUrl = item.url
        this.imageReviewDialog = true
      }
    },
    /**
     * 移除文件
     * @param item 图片信息元素
     */
    removeImage (item) {
      if (item && item.id) {
        this.$confirm('确实确定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeByIds([item.id], data => {
            if (data && data.code === ResultCode.OK) {
              this.$message.success('移除成功')
              this.reset()
            }
          })
        }).catch(() => {
        })
      } else {
        this.$message.error('数据错误')
      }
    },
    /**
     * 下载图片文件
     * @param item 图片信息元素
     */
    downloadImage (item) {
      if (item && item.url && !this.downLoading) {
        const url = item.url
        this.downLoading = true
        const fileName = url.toString().substring(url.lastIndexOf('/') + 1)
        this.$message.success(fileName)
        downloadUrlFile(url, fileName)
        this.downLoading = false
      }
    },
    /**
     * 选择图片
     * @param item 图片信息元素
     */
    handleSelect (item) {
      if (item) {
        if (this.multiple) {
          item.select = !item.select
        } else {
          if (!item.select) {
            // 没有被选中，则取出所有选中，然后选中这个
            this.list.forEach(item2 => {
              item2.select = false
            })
            this.queryList.forEach(item2 => {
              item2.select = false
            })
          }
          item.select = !item.select
        }
      }
    },
    /**
     * 重置
     */
    reset () {
      this.queryData()
    },
    /**
     * 获取选择的文件列表
     * @return {Array<Object>} 选择文件的文件列表
     */
    getSelectFiles () {
      const temp = []
      if (this.queryList && typeof this.queryList === 'object') {
        this.queryList.forEach(item => {
          if (item.select) {
            temp.push(item)
          }
        })
      }
      if (this.list && typeof this.list === 'object') {
        this.list.forEach(item => {
          if (item.select) {
            temp.push(item)
          }
        })
      }
      return temp
    }
  },
  watch: {
    name () {
      this.queryData()
    }
  }
}
</script>

<style scoped lang="scss">

  $itemWidth: 140px;
  $itemHeight: 140px;

.fileCollectionWrapper{
  width: 100%;

  .list{
    list-style: none;
    display: block;
    width: 100%;
    margin-top: -16px;

    .li{
      display: inline-block;
      width: $itemWidth;
      height: $itemHeight;
      margin: 10px 17px;
      overflow: hidden;

      .cardSelect {
        border: 3px solid #ee2211a0 !important;
      }

      .card{
        width: $itemWidth;
        height: $itemHeight;
        padding: 0;
        margin: 0;
        border: 3px solid transparent;
        overflow: hidden;
        cursor: pointer;

        .wrapper{
          display: block;
          width: $itemWidth;
          height: $itemHeight;
          position: relative;

          .loading{
            font-size: 50px;
            margin-left: 45px;
            margin-top: 45px;
          }

          .img{
            display: block;
            width: $itemWidth;
            height: $itemHeight;
          }

          .maskUploading{
            display: block;
            width: $itemWidth;
            height: $itemHeight;
            position: absolute;
            top: 0;
            left: 0;
            background: rgba(155,155,155,0.2);

            .maskIcon{
              display: block;
              width: $itemWidth;
              height: $itemHeight;
              position: absolute;
              top: 0;
              left: 0;
              background: rgba(155,155,155,0.7);
              text-align: center;

              .progress{
                margin-top: 40px;
              }

            }

          }

          .maskMenu{
            display: none;
            visibility: hidden;
            width: $itemWidth;
            height: $itemHeight;
          }
        }

      }

      .card:hover{
        .maskMenu{
          display: block;
          visibility: visible;
          width: $itemWidth;
          height: $itemHeight;
          position: absolute;
          top: 0;
          left: 0;
          background: rgba(200,200,200,0.5);
          text-align: center;
          padding-top: 50px;
        }
      }

    }

  }

}
</style>

<!--suppress CssUnusedSymbol -->
<style lang="css">
  .el-card__body{
    padding: 0;
  }
</style>
